package com.xxchat.service.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import com.xxchat.entity.dto.SysSettingDTO;
import com.xxchat.entity.dto.TokenUserInfoDTO;
import com.xxchat.entity.dto.UserContactSearchResultDTO;
import com.xxchat.entity.enums.*;
import com.xxchat.entity.po.*;
import com.xxchat.entity.query.*;
import com.xxchat.exception.BusinessException;
import com.xxchat.mappers.*;
import com.xxchat.redis.RedisComponent;
import com.xxchat.utils.CopyUtils;
import org.springframework.stereotype.Service;

import com.xxchat.entity.vo.PaginationResultVO;
import com.xxchat.service.UserContactService;
import com.xxchat.utils.StringTools;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;


/**
 * 联系人表 业务接口实现
 */
@Service("userContactService")
public class UserContactServiceImpl implements UserContactService {

    @Resource
    private UserContactMapper<UserContact, UserContactQuery> userContactMapper;

    @Resource
    private UserInfoMapper<UserInfo, UserInfoQuery> userInfoMapper;

    @Resource
    private GroupInfoMapper<GroupInfo, GroupInfoQuery> groupInfoMapper;

    @Resource
    private ChatSessionMapper<ChatSession, ChatSessionQuery> chatSessionMapper;

    @Resource
    private ChatSessionUserMapper<ChatSessionUser, ChatSessionQuery> chatSessionUserMapper;

    @Resource
    private ChatMessageMapper<ChatMessage, ChatMessageQuery> chatMessageMapper;

    @Resource
    private RedisComponent redisComponent;

    /**
     * 根据条件查询列表
     */
    @Override
    public List<UserContact> findListByParam(UserContactQuery param) {
        return this.userContactMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(UserContactQuery param) {
        return this.userContactMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<UserContact> findListByPage(UserContactQuery param) {
        int count = this.findCountByParam(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<UserContact> list = this.findListByParam(param);
        PaginationResultVO<UserContact> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(UserContact bean) {
        return this.userContactMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<UserContact> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userContactMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<UserContact> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userContactMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 多条件更新
     */
    @Override
    public Integer updateByParam(UserContact bean, UserContactQuery param) {
        StringTools.checkParam(param);
        return this.userContactMapper.updateByParam(bean, param);
    }

    /**
     * 多条件删除
     */
    @Override
    public Integer deleteByParam(UserContactQuery param) {
        StringTools.checkParam(param);
        return this.userContactMapper.deleteByParam(param);
    }

    /**
     * 根据ContactIdAndUserId获取对象
     */
    @Override
    public UserContact getUserContactByContactIdAndUserId(String contactId, String userId) {
        return this.userContactMapper.selectByContactIdAndUserId(contactId, userId);
    }

    /**
     * 根据ContactIdAndUserId修改
     */
    @Override
    public Integer updateUserContactByContactIdAndUserId(UserContact bean, String contactId, String userId) {
        return this.userContactMapper.updateByContactIdAndUserId(bean, contactId, userId);
    }

    /**
     * 根据ContactIdAndUserId删除
     */
    @Override
    public Integer deleteUserContactByContactIdAndUserId(String contactId, String userId) {
        return this.userContactMapper.deleteByContactIdAndUserId(contactId, userId);
    }

    @Override
    public UserContactSearchResultDTO searchContact(String userId, String contactId) {
        UserContactTypeEnum typeEnum = UserContactTypeEnum.getByPrefix(contactId);
        if (typeEnum == null) {
            return null;
        }
        UserContactSearchResultDTO result = new UserContactSearchResultDTO();
        switch (typeEnum) {
            case USER:
                UserInfo userInfo = this.userInfoMapper.selectByUserId(contactId);
                if (userInfo == null) {
                    return null;
                }
                result = CopyUtils.copy(userInfo, UserContactSearchResultDTO.class);
                break;
            case GROUP:
                GroupInfo groupInfo = this.groupInfoMapper.selectByGroupId(contactId);
                if (groupInfo == null) {
                    return null;
                }
                result.setNickName(groupInfo.getGroupName());
                break;
        }
        result.setContactType(typeEnum.getType()).setContactId(contactId);
        // status 设置
        // 如果搜的是自己
        if (userId.equals(contactId)) {
            result.setStatus(UserContactStatusEnum.MYSELF.getStatus());
            result.setStatusName(UserContactStatusEnum.MYSELF.getDesc());
            return result;
        }
        // 查看是否是好友
        UserContact userContact = this.userContactMapper.selectByContactIdAndUserId(contactId, userId);
        if (userContact == null) {
            // 非好友
            result.setStatus(UserContactStatusEnum.NOT_FRIEND.getStatus());
            result.setStatusName(UserContactStatusEnum.NOT_FRIEND.getDesc());
            return result;
        }
        // 其它状态
        result.setStatus(userContact.getStatus());
        if (typeEnum.equals(UserContactTypeEnum.USER)) {
            result.setStatusName(Objects.requireNonNull(UserContactStatusEnum.getByStatus(userContact.getStatus())).getDesc());
        } else {
            result.setStatusName(Objects.requireNonNull(GroupStatusEnum.getByStatus(userContact.getStatus())).getDesc());
        }
        return result;
    }

    @Override
    public List<UserContact> loadContactList(TokenUserInfoDTO userInfoDTO, UserContactTypeEnum contactTypeEnum) {
        if (UserContactTypeEnum.USER.equals(contactTypeEnum)) {
            // 好友
            return this.userContactMapper.selectUserContactList(userInfoDTO.getUserId(), contactTypeEnum.getType(), UserContactStatusEnum.FRIEND.getStatus());
        } else if (UserContactTypeEnum.GROUP.equals(contactTypeEnum)) {
            // 群组
            return this.userContactMapper.selectGroupContactList(userInfoDTO.getUserId(), contactTypeEnum.getType(), UserContactStatusEnum.FRIEND.getStatus());
        } else if (UserContactTypeEnum.MYSELF.equals(contactTypeEnum)) {
            // 自己的群组
            return this.userContactMapper.selectMyGroupContactList(userInfoDTO.getUserId(), UserContactTypeEnum.GROUP.getType());
        } else {
            return Collections.emptyList();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeContact(String userId, String contactId, UserContactStatusEnum userContactStatusEnum) {
        UserContactStatusEnum status = UserContactStatusEnum.getByStatus(userContactStatusEnum.getStatus());
        if (null == status) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }

        UserContact contact = this.userContactMapper.selectByContactIdAndUserId(contactId, userId);
        UserContact contact1 = this.userContactMapper.selectByContactIdAndUserId(userId, contactId);
        if (null == contact || null == contact1 || UserContactStatusEnum.FRIEND.getStatus().equals(contact1.getStatus())) {
            // 互相是好友才能删除/拉黑
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }

        // 移除/拉黑好友
        UserContact userContact = new UserContact();
        userContact.setStatus(status.getStatus());
        this.userContactMapper.updateByContactIdAndUserId(userContact, userId, contactId);
        // 好友中对自己的状态也改变
        UserContact userContact1 = new UserContact();
        if (UserContactStatusEnum.DEL.equals(status)) {
            userContact1.setStatus(UserContactStatusEnum.DEL_BE.getStatus());
        } else if (UserContactStatusEnum.BLACKLIST.equals(status)) {
            userContact1.setStatus(UserContactStatusEnum.BLACKLIST_BE.getStatus());
        } else {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        this.userContactMapper.updateByContactIdAndUserId(userContact1, contactId, userId);
        // 从缓存中删除我的好友 和 好友的我
        this.redisComponent.removeUserContact(userId, contactId);
        this.redisComponent.removeUserContact(contactId, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addContact4Robot(String userId) {
        SysSettingDTO setting = redisComponent.getSysSetting();
        String contactId = setting.getRobotUid();
        String contactName = setting.getRobotNickName();
        String message = setting.getRobotWelcome();
        message = HtmlUtils.htmlEscape(message);

        // 增加机器人为好友
        UserContact userContact = new UserContact();
        userContact.setUserId(userId);
        userContact.setContactId(contactId);
        userContact.setContactType(UserContactTypeEnum.USER.getType());
        userContact.setCreateTime(new Date());
        userContact.setLastUpdateTime(new Date());
        userContact.setStatus(UserContactStatusEnum.FRIEND.getStatus());
        this.userContactMapper.insert(userContact);

        // 增加会话信息
        String sessionId = StringTools.getChatSessionId4User(new String[]{userId, contactId});
        ChatSession chatSession = new ChatSession();
        chatSession.setSessionId(sessionId);
        chatSession.setLastMessage(message);
        chatSession.setLastReceiveTime(System.currentTimeMillis());
        this.chatSessionMapper.insert(chatSession);

        // 增加会话人信息
        ChatSessionUser chatSessionUser = new ChatSessionUser();
        chatSessionUser.setUserId(userId);
        chatSessionUser.setContactId(contactId);
        chatSessionUser.setSessionId(sessionId);
        chatSessionUser.setContactName(contactName);
        this.chatSessionUserMapper.insert(chatSessionUser);

        // 增加聊天消息
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSessionId(sessionId);
        chatMessage.setMessageType(MessageTypeEnum.CHAT.getType());
        chatMessage.setMessageContent(message);
        chatMessage.setSendUserId(contactId);
        chatMessage.setSendUserNickName(contactName);
        chatMessage.setSendTime(System.currentTimeMillis());
        chatMessage.setContactId(userId);
        chatMessage.setContactType(UserContactTypeEnum.USER.getType());
        chatMessage.setStatus(MessageStatusEnum.SENDED.getStatus());
        this.chatMessageMapper.insert(chatMessage);
    }
}